﻿using System;
using System.Web;
using Web.Model;
using NHibernate;
using Web.Extensions;
using System.Web.Mvc;

namespace Web.HelperClasses
{
    public class CommentNotifier
    {
        private HeadComment headComment;
        private ISession session;

        private const string NewCommentTemplate = @"Уважаемый {0}.<br/> 
Пользователь <a href='{2}'>{1}</a> ответил на ваш комментарий:<br/>
<br/>
{3}<br/>
<br/>
<a href='{4}'>Прочитать обсуждение</a>
";

        public CommentNotifier(int id, ISession session)
        {
            this.session = session;
            headComment = session.Get<HeadComment>(id);
            if (headComment == null) throw new InvalidOperationException("Исходный комментарий не найден");
        }

        public void NotifyNewComment(CommentBase newComment)
        {
            User author = headComment.Author;
            if (author == null) throw new InvalidOperationException("Пользователь не найден");
            if (author.NotifyAuthorCommentReplied && !String.IsNullOrEmpty(author.Email))
            {
                UrlHelper urlHelper = UrlHelperExtensions.GetUrlHelper();
                string discussionLink = "";
                if (headComment.Story.GetType().FullName == typeof(Project).FullName)
                {
                    discussionLink = urlHelper.ActionAbsolute("View", "Project", new { Id = headComment.Story.Id }).AbsoluteUri;
                }
                Notification newNotification = new Notification()
                {
                    Subject = "На ваш комментарий ответили",
                   // Recipient = organizer,
                    Email = author.NotificationEmail,
                    Body = String.Format(NewCommentTemplate,
                        author.DisplayName,
                        HttpUtility.HtmlEncode(newComment.Author.DisplayName),
                        urlHelper.ActionAbsolute("View", "User", new { Id = newComment.Author.Id }).AbsoluteUri,
                        HttpUtility.HtmlEncode(newComment.Text),
                        discussionLink
                    )
                };
                session.Save(newNotification);
            }
        }
    }
}